package com.simba.security;

import cn.hutool.core.util.StrUtil;
import com.simba.response.JSONAuthentication;
import com.simba.response.Result;
import com.simba.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 匿名用户访问无权限资源时的异常
 */
@Slf4j
@Component
public class MyAuthenticationEntryPoint extends JSONAuthentication implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.info("用户登录认证过程发生未知错误,未检测到有效的token信息");
        Result result = null;
        if(request.getAttribute("errorMessage") == null){
            result = Result.error().message(e.getMessage());
        }else {
            result = Result.error().message(request.getAttribute("errorMessage").toString());
        }
        this.WriteJSON(request, response, result);
    }
}
